// pages/change-password/change-password.js
import authService from "../../services/auth.service";
import personalCenterService from "../../services/personal-center.service";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',
    verifyCode: "",
    verifyCodeKey: "",
    verifyCodeUrl: "",
  },
  updateVerifyCode: async function () {
    try {
      const res = await authService.getVerifyCode();
      this.setData({
        verifyCodeUrl: `${res.data.data?.image}`,
        verifyCodeKey: res.data.data?.key,
      });
    } catch (err) {
      wx.showToast({
        title: err.data && err.data.message || err.errMsg,
        icon: 'error'
      });
      throw err;
    }
  },

  async save() {
    try {
      if (this.data.oldPassword == null || this.data.oldPassword == "") {
        wx.showToast({
          title: '请输入旧密码',
          icon: "error"
        });
        return;
      }
      if (this.data.newPassword == null || this.data.newPassword == "") {
        wx.showToast({
          title: '请输入新密码',
          icon: "error"
        });
        return;
      }
      if (!REGEX_PASSWORD.test(this.data.password)) {
        wx.showToast({
          title: '密码格式应为8-18位数字、字母、符号的任意两种组合',
          icon: "error"
        });
        return;
      }
      if (this.data.confirmPassword == null || this.data.confirmPassword == "") {
        wx.showToast({
          title: '请输入确认密码',
          icon: "error"
        });
        return;
      }
      if (this.data.password != this.data.confirmPassword) {
        wx.showToast({
          title: '两次密码输入不一致',
          icon: "error"
        });
        return;
      }
      if (this.data.verifyCode == null || this.data.verifyCode == "") {
        wx.showToast({
          title: '请输入验证码',
          icon: "error"
        });
        return;
      }
      const body = {
        oldPassword: this.data.oldPassword,
        newPassword: this.data.newPassword,
        confirmPassword: this.data.confirmPassword,
        verifyCodeKey: this.data.verifyCodeKey,
        verifyCode: this.data.verifyCode,
      }
      await personalCenterService.changePassword(body);

      wx.showToast({
        title: '密码修改成功',
        icon: "success"
      });
      wx.navigateTo({
        url: '/pages/login/login',
      });
    } catch (err) {
      wx.showToast({
        title: err.data && err.data.message || err.errMsg,
        icon: 'error'
      });
      throw err;
    } finally {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.updateVerifyCode();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})